package com.qyer.commons.concurrent.assemblingline;

import com.qyer.commons.Context;
import com.qyer.commons.concurrent.assemblingline.creator.BasicStatistic;
import com.qyer.commons.concurrent.assemblingline.creator.BasicStatisticCreator;

/**
 * User: Z J Wu Date: 2016/06/12 Time: 10:11 Package: com.qyer.commons.concurrent.assemblingline
 */
/*
* 这里使用BasicStatistic是因为如果不抽象成类, 就需要直接通过name+后缀的方式存储atomicLong
* 每次方法调用name+后缀生成key的时候, 都会调用stringbuilder的tostring, 这个方法会调用string的构造方法
* 绕过虚拟机缓存直接创建无数重复的string对象. 如果使用name作为key, 因为没有调用拼接字符串, 因此
* 不会创建过多的对象.
* */
public class StatisticContext extends Context {

  public StatisticContext() {
  }

  // 单个增加
  public synchronized void reportSuccess(String name, ProcessMode mode) throws
    AssemblingLineException {
    BasicStatistic statistic = putValueIfNull(name, BasicStatisticCreator.getInstance(), mode);
    statistic.getSuccessCount().incrementAndGet();
  }

  public synchronized void reportFailure(String name, ProcessMode mode) throws
    AssemblingLineException {
    BasicStatistic statistic = putValueIfNull(name, BasicStatisticCreator.getInstance(), mode);
    statistic.getFailureCount().incrementAndGet();
  }

  public synchronized void reportTimeCost(String name, long timeCost, ProcessMode mode) throws
    AssemblingLineException {
    BasicStatistic statistic = putValueIfNull(name, BasicStatisticCreator.getInstance(), mode);
    statistic.getTotalTimeCost().addAndGet(timeCost);
  }

}
